import {Promise} from 'es6-promise';
import {Db, MongoClient, Collection, MongoClientOptions} from "mongodb";

import {MongoCfg, MongoColls, MongoCollNames} from "../config/mongo";
import { mongo } from 'mongoose';

export default class Mongo {
    private _db: Db = null;

    connect(isDebug: boolean): Promise<Db> {
        return MongoClient.connect(this.connectUrl(isDebug), <MongoClientOptions>MongoCfg.options)
            .then( (db) => {
                this._db = db;
                return db;
            });
    }

    get db(): Db { return this._db; }

    collection(coll: MongoColls): Collection {
        if(!this._db){
            throw new Error('MongoDb is not connected!');
        }
        return this._db.collection( MongoCollNames[coll] );
    }

    connectUrl(isDebug: boolean): string {
        let db = MongoCfg.database;
        let serverCfg = isDebug ? MongoCfg.dev : MongoCfg.prod;
        let auth = serverCfg.auth;
        let servers = serverCfg.servers;
        let hosts: string = servers.reduce( (p: string, c: any) => `${p&&(p + ',')}${c.addr}:${c.port}`, '');
        return `mongodb://${auth.user}:${auth.password}@${hosts}/${db}`;
    }
}
